package com.handler;

import com.message.ChatReqMessage;
import com.message.LoginReqMessage;
import com.message.resp.ChatResp;
import com.message.resp.LoginResp;
import com.protocol.SharedMessageCodec;
import com.session.ChatServerContext;
import com.session.ChatServerContextFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * server 处理聊天客户端登录
 */
@ChannelHandler.Sharable
@Slf4j
public class ChatLoginHandler extends SimpleChannelInboundHandler<LoginReqMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginReqMessage msg) throws Exception {
        log.debug("登录请求：{}", msg);
        LoginResp loginResp = new LoginResp();
        loginResp.setLoginSuccess(true);
        ctx.writeAndFlush(loginResp);
        log.debug("将用户【{}】添加到全局的聊天室上下文中", msg.getUserName());

        ChatServerContextFactory.getInstance().addUserNameAndChannel(msg.getUserName(), ctx.channel());

        ctx.fireChannelRead(msg);
    }
}
